﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO;

namespace BranchTool
{
    public partial class frmMain : Form
    {
        private List<FileList> _fileList = new List<FileList>();
        private string _branchPath = "";

        public frmMain()
        {
            InitializeComponent();
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            SaveSetting();
            this.txtMessage.Clear();
            this.txtFileList.Text = this.txtFileList.Text.Replace("/", "\\");
            AssortFile(this.txtFileList.Text.Trim());

            string strBranchPath = this.txtBranchPath.Text.Trim();

            #region Create BranchPath with date-time
            if (!Directory.Exists(strBranchPath))
            {
                Directory.CreateDirectory(strBranchPath);
            }
            if (strBranchPath.EndsWith("\\"))
            {
                strBranchPath += DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss");
            }
            else
            {
                strBranchPath = strBranchPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss");
            }
            if (!Directory.Exists(strBranchPath))
            {
                Directory.CreateDirectory(strBranchPath);
            }

            #endregion

 
            foreach (FileList file in this._fileList)
            {
                string strFileFullPath ="";
                if(file.FileFolder.IndexOf("EventMail") > -1)
                {
                    strFileFullPath = FindFileInFolder(this.txtPublishPath.Text.Trim() + "\\EventMail",file.FileName);
                }
                else if(file.FileFolder.IndexOf("SystemAdmin") > -1)
                {
                    strFileFullPath = FindFileInFolder(this.txtPublishPath.Text.Trim() + "\\SystemAdmin", file.FileName);
                }
                else if (file.FileFolder.IndexOf("NewMediaClient") > -1)
                {
                    strFileFullPath = FindFileInFolder(this.txtPublishPath.Text.Trim() + "\\NewMediaClient", file.FileName);
                }
                else if ((file.FileFolder.IndexOf("NewMedia") > -1) && file.FileFolder.IndexOf("NewMediaClient") == -1)
                {
                    strFileFullPath = FindFileInFolder(this.txtPublishPath.Text.Trim() + "\\NewMedia", file.FileName);
                }

                else
                {                
                    strFileFullPath = FindFileInFolder(file.FileName);
                }

                Publish2Branch(this.txtPublishPath.Text.Trim(), strBranchPath, strFileFullPath);
                RecordMessage("Copy file from :" + file.FileFolder + "\\" + file.OriginalName + "\r\n--->:" + _branchPath.Replace(this.txtBranchPath.Text.Trim(), ""));

            }

        }


        /// <summary>
        /// Save the lastest selected folders & filelist as default values.
        /// </summary>
        private void SaveSetting()
        {

            SettingHelp.Instance.SetSetting(this.txtPublishPath.Text.Trim(), this.txtCodePath.Text.Trim(), this.txtBranchPath.Text.Trim(), this.txtFileList.Text.Trim());
        }

        private void RecordMessage(string strMessage)
        {
            this.txtMessage.Text += strMessage + "\r\n\r\n";
            Application.DoEvents();
        }

        private string GetNameFromPath(string strPath)
        {
            if (strPath.StartsWith("\\"))
            {
                strPath = strPath.Substring(1);
            }

            int index = strPath.LastIndexOf("\\");
            if (index == -1)
            {
                return strPath;
            }
            return strPath.Substring(index + 1);
        }

        private string GetFolderFromPath(string strPath)
        {
            if (strPath.StartsWith("\\"))
            {
                strPath = strPath.Substring(1);
            }

            int index = strPath.LastIndexOf("\\");
            if (index == -1)
            {
                return "";
            }
            return strPath.Substring(0, index);
        }

        private void Publish2Branch(string strPublishPath, string strBranchPath, string strPublishFile)
        {
            if (strPublishFile == "")
            {
                return;
            }

            CreatePath(strPublishPath, strBranchPath, strPublishFile);

            try
            {
                File.Copy(strPublishFile, _branchPath);
            }
            catch (Exception ex)
            {
                RecordMessage("Error:" + ex.Message);
            }

        }

        private void CreatePath(string strPublishPath, string strBranchPath, string strPublishFile)
        {
            string relativePath = strPublishFile.Replace(strPublishPath, "");

            if (relativePath.StartsWith("\\"))
            {
                relativePath = relativePath.Substring(1);
            }
            int index = relativePath.IndexOf("\\");
            _branchPath = strBranchPath + "\\" + relativePath;

            string temp = "";

            while (index > -1)
            {
                temp = temp + "\\" + relativePath.Substring(0, index);

                if (!Directory.Exists(strBranchPath + temp))
                {
                    Directory.CreateDirectory(strBranchPath + temp);
                }
                relativePath = relativePath.Substring(relativePath.IndexOf("\\") + 1);
                index = relativePath.IndexOf("\\");
            }
        }

        private void AssortFile(string strFileList)
        {
            _fileList.Clear();
            Regex reg = new Regex(@"(\\|\/)?.*\..*");
            Match match = reg.Match(strFileList);
            while (match.Success)
            {
                FileList file = new FileList();

                string FindFileName = match.Value.Replace("\r", "");
                string strFileName = GetNameFromPath(FindFileName);
                string strFilePath = GetFolderFromPath(FindFileName);

                file.OriginalName = strFileName;
                file.FileName = ReplaceFileName(strFileName);
                file.FileFolder = strFilePath;
                
                this._fileList.Add(file);

                match = match.NextMatch();
            }
        }

        private string ReplaceFileName(string strFileName)
        {
            if (strFileName.ToLower().EndsWith(".cs"))
            {
               return strFileName = GetProjectDllName(strFileName);
            }

            return strFileName;
        }


        private string GetProjectDllName(string strFileName)
        {
            string strCodeFilePath = FindFileInFolder(this.txtCodePath.Text.Trim(), strFileName);

            string strProjectName = strCodeFilePath.Replace(this.txtCodePath.Text.Trim(), "");

            if (strProjectName.StartsWith("\\"))
            {
                strProjectName = strProjectName.Substring(1);
            }
            if (strProjectName.IndexOf("\\") > -1)
            {
                strProjectName = strProjectName.Substring(0, strProjectName.IndexOf("\\"));
            }

            if ((strProjectName == "BaseAssembly"))
            {
                return "BaseAssembly.dll";
            }
            else if (strProjectName == "BusinessRule")
            {
                return "BusinessRule.dll";
            }
            else if (strProjectName == "Common")
            {
                return "Common.dll";
            }
            else if (strProjectName == "DataAccess")
            {
                return "DataAccess.dll";
            }
            else if (strProjectName == "EventMail")
            {
                return "EventMail.dll";
            }
            else if (strProjectName == "NewMedia")
            {
                return "NewMedia.dll";
            }
            else if (strProjectName == "NewMediaClient")
            {
                return "NewMediaClient.dll";
            }
            else if (strProjectName == "MailLink")
            {
                return "MailLink.dll";
            }
            else if (strProjectName == "Model")
            {
                return "Model.dll";
            }
            else if (strProjectName == "SystemAdmin")
            {
                return "SystemAdmin.dll";
            }
            return "";

        }


        private string FindFileInFolder(string strFileName)
        {
            return FindFileInFolder(this.txtPublishPath.Text, strFileName);
        }


        private string FindFileInFolder(string strFolder, string strFileName)
        {

            try
            {
                foreach (string strFilePath in Directory.GetFiles(strFolder))
                {
                    FileInfo info = new FileInfo(strFilePath);
                    if (info.Name == strFileName)
                    {
                        return strFilePath;
                    }
                }

                foreach (string strFolderPath in Directory.GetDirectories(strFolder))
                {
                    string strResult = FindFileInFolder(strFolderPath, strFileName);

                    if (strResult != "")
                    {
                        return strResult;
                    }
                }
            }
            catch(Exception ex)
            {
                RecordMessage("Error:" + ex.Message);
            }            

            return "";
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnSelectPublisthPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            dlg.Description = "Select Publisth Path";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (dlg.SelectedPath != "")
                {
                    this.txtPublishPath.Text = dlg.SelectedPath;
                }
            }

        }

        private void btnSelectCodePath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            dlg.Description = "Select Code Path";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (dlg.SelectedPath != "")
                {
                    this.txtCodePath.Text = dlg.SelectedPath;
                }
            }
        }

        private void btnSelectBranchPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            dlg.Description = "Select Branch Path";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (dlg.SelectedPath != "")
                {
                    this.txtBranchPath.Text = dlg.SelectedPath;
                }
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            PathSetting set = SettingHelp.Instance.GetSetting();
            if (set == null)
                return;
            this.txtBranchPath.Text = set.BranchPath;
            this.txtCodePath.Text = set.CodePath;
            this.txtFileList.Text = set.FileList.Replace("\n", "\r\n");
            this.txtPublishPath.Text = set.PublishPath;
        }
    }
}
